/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { Component } from "react";
import { connect } from "dva";
import moment from "moment/moment";
import { debounce } from "lodash";
import { Form, Button, DatePicker } from "antd";
import StandardTable from "@/components/StandardTable";
import { getOrderQuery } from "@/services/express";
import AsyncDownLoad from "@/components/DownloadBar/AsyncDownLoad";
import { Yzs } from "@/components/Select";
import styles from "../PostList/style.less";

const { RangePicker } = DatePicker;
const FormItem = Form.Item;
const dateFormat = "YYYY-MM-DD";
const formItemLayout = {
  labelCol: {
    xs: { span: 0 },
    sm: { span: 8 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 },
  },
};
@connect(({ loading, submissionRecords }) => ({
  recordList: submissionRecords.recordList,
  downLoadURL: submissionRecords.downLoadURL,
  listLoading: loading.effects["submissionRecords/getOrderQuery"],
}))
@Form.create()
export default class StatisticalData extends Component {
  state = {
    cm_id: "all",
    page: 1,
    fieldsValue: {}
  };

  componentDidMount(){
    this.getList({})
  }

  getList = ({page=1, dl=0}) => {
    const { dispatch } = this.props
    this.getFormValues(res=>{
      dispatch({
        type: "submissionRecords/getOrderQuery",
        payload: {
          page,
          dl,
          ...res,
        }
      })
      this.setState({page})
    })
  }

  getFormValues = then => {
    const { form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
      };
      const { date } = fieldsValue;
      if (date) {
        values.date = date.map(d => moment(d).format("YYYY-MM-DD"));
        const [start, end] = values.date;
        values.beginTime = start;
        values.endTime = end;
        delete values.date;
      }
      this.setState({fieldsValue:values})
      then(values);
    });
  };

  handleStandardTableChange = debounce(pagination => {
    const { current } = pagination
    this.getList({page:current})
  },500,{
    leading: true,
    trailing: false
  })

  handleSearchForthe = debounce(
    e => {
      e.preventDefault();
      this.getList({})
    },
    500,
    {
      leading: true,
      trailing: false,
    }
  );

  dataClick = data => {
    const setFieldsValueDate = {
      startDate: moment()
        .startOf("day")
        .subtract(data, "days"),
      endDate: moment()
        .endOf("day")
        .subtract(data == 1 ? data : 0, "days"),
    };
    this.props.form.setFieldsValue({
      date: [setFieldsValueDate.startDate, setFieldsValueDate.endDate],
    });
  };

  getDownLoadURL(){
    const { page, fieldsValue } = this.state
    return getOrderQuery({
      // page,
      dl: 1,
      ...fieldsValue
    })
  }

  range = (start, end) => {
    const result = [];
    for (let i = start; i < end; i++) {
      result.push(i);
    }
    return result;
  };

  disabledDate = current => {
    return (
      current &&
      current >
        moment()
          .endOf("day")
          .subtract(0, "days")
    );
  };

  render() {
    const {
      form,
      columns,
      recordList,
      listLoading,
    } = this.props;
    const { cm_id } = this.state
    const { getFieldDecorator } = form;
    const defaultSelectDate = {
      startDate: moment()
        .startOf("day")
        .subtract(6, "days"),
      endDate: moment()
        .endOf("day")
        .subtract(0, "days"),
    };
    const disabled = recordList.list.length == 0

    return (
      <div>
        <Form
          onSubmit={this.handleSearchForthe}
          className={styles["search-form"]}
          layout="inline"
        >
          <FormItem>
            <a className={styles.select_date} onClick={() => this.dataClick(1)}>
              昨日
            </a>
            <a className={styles.select_date} onClick={() => this.dataClick(6)}>
              近7日
            </a>
            <a className={styles.select_date} onClick={() => this.dataClick(29)}>
              近30日
            </a>
          </FormItem>
          <FormItem {...formItemLayout} className={styles.data}>
            {getFieldDecorator("date", {
              initialValue: [defaultSelectDate.startDate, defaultSelectDate.endDate],
            })(
              <RangePicker
                style={{ width: "280px" }}
                placeholder={["开始日期", "结束日期"]}
                disabledDate={this.disabledDate}
              />
            )}
          </FormItem>
          <FormItem {...formItemLayout} className={styles.data}>
            {getFieldDecorator("cm_id",{
              initialValue: cm_id
            })(
              <Yzs allowClear/>
            )}
          </FormItem>
          <FormItem>
            <span className={styles.submitButtons}>
              <Button
                type="primary"
                htmlType="submit"
                key="search"
                loading={listLoading}
                icon="search"
              >
                查询
              </Button>
            </span>
            <div
              style={{
                paddingBottom: "24px",
                marginLeft: "16px",
                display: "inline-block",
              }}
            >
              <AsyncDownLoad requestFunc={this.getDownLoadURL.bind(this)}>
                <Button type="primary" icon="download" disabled={disabled}>
                  下载
                </Button>
              </AsyncDownLoad>              
            </div>
          </FormItem>
        </Form>
        <StandardTable
          rowKey={record=>record.create_time}
          loading={listLoading}
          data={recordList}
          columns={columns}
          onChange={this.handleStandardTableChange}
        />
      </div>
    );
  }
}
